import $ from 'jquery';
import {
  BOOK_ADD,
  BOOK_UPDATE,
  BOOK_REMOVE,
  BOOK_SAVING,
  BOOK_SWITCH,
  BOOK_LIST_RESET,
  NOTE_LIST_RESET
} from './actionTypes';

export function switchBook(book) {
  return {
    type: BOOK_SWITCH,
    book: book
  }
}
export function resetBookList(books) {
  return {
    type: BOOK_LIST_RESET,
    items: books
  }
}

export function fetchBookList() {
  return function (dispatch) {
    $.get("/api/book").done((resp)=> {
      dispatch(resetBookList(resp.data))
    });
  }
}

export function updateBook(_id, name) {
  return function (dispatch) {
    dispatch({type: BOOK_SAVING});
    $.ajax({
      'url': `/api/book/${_id}`,
      'method': 'PUT',
      'data': {name}
    }).done(function (resp) {
      dispatch({
        type: BOOK_UPDATE,
        book: resp.data
      });
    });
  }
}

export function removeBook(_id) {
  return function (dispatch) {
    dispatch({type: BOOK_SAVING});
    $.ajax({
      'url': `/api/book/${_id}`,
      'method': 'DELETE',
      'data': {name}
    }).done(function () {
      dispatch({
        type: BOOK_REMOVE,
        _id
      });
    });
  }
}

export function switchBookFromRemote(_id) {
  return function (dispatch) {
    dispatch({
      type: NOTE_LIST_RESET,
      items: []
    });
    $.ajax({
      'url': `/api/book/${_id}`,
      'method': 'GET'
    }).done(function (resp) {
      dispatch(switchBook(resp.data));
      dispatch({
        type: NOTE_LIST_RESET,
        items: resp.data.notes
      });
    });
  };
}
